package com.agileai.hotweb.bizmoduler.core;

import java.util.ArrayList;
import java.util.List;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.domain.db.Column;
import com.agileai.domain.db.Table;

public class ResourceUploadServiceImpl extends BaseService 
	implements ResourceUploadService{
	private String primaryKey = null;
	private String bizIdField = null;
	private String resIdField = null;

	@Override
	public void createResourceRelation(String bizId, String resId) {
		String statementId = sqlNameSpace+"."+"insertRecord";
		DataParam param = new DataParam();
		String primaryKeyValue = KeyGenerator.instance().genKey();
		param.put(getPrimaryKey(),primaryKeyValue);
		param.put(bizIdField,bizId);
		param.put(resIdField,resId);
		this.daoHelper.insertRecord(statementId, param);
	}

	@Override
	public void deleteResourceRelations(List<String> refIdList) {
		String statementId = sqlNameSpace+"."+"deleteRecord";
		List<DataParam> paramList = new ArrayList<DataParam>();
		for (int i=0;i < refIdList.size();i++){
			String refId = refIdList.get(i);
			DataParam param = new DataParam();
			param.put(getPrimaryKey(),refId);
			paramList.add(param);
		}
		this.daoHelper.batchDelete(statementId, paramList);
	}

	@Override
	public List<DataRow> findResourceRelations(String bizId) {
		DataParam param = new DataParam("BIZ_ID",bizId);
		String statementId = sqlNameSpace+"."+"findRecords";
		List<DataRow> result = this.daoHelper.queryRecords(statementId, param);
		return result;
	}

	public List<DataRow> findResourceRelations(DataParam param) {
		String statementId = sqlNameSpace+"."+"findRecords";
		List<DataRow> result = this.daoHelper.queryRecords(statementId, param);
		return result;
	}
	
	public String getPrimaryKey() {
		if (this.primaryKey == null){
			Table table = getTableMetaData(tableName);
			List<Column> columns = table.getColumns();			
			int count = columns.size();
			for (int i=0;i < count;i++){
				Column column = columns.get(i);
				if (column.isPK()){
					this.primaryKey = column.getName();
					break;
				}
			}
		}
		return primaryKey;
	}

	public void setPrimaryKey(String primaryKey) {
		this.primaryKey = primaryKey;
	}

	public String getBizIdField() {
		return bizIdField;
	}

	public void setBizIdField(String bizIdField) {
		this.bizIdField = bizIdField;
	}

	public String getResIdField() {
		return resIdField;
	}

	public void setResIdField(String resIdField) {
		this.resIdField = resIdField;
	}
}